<template>
    <view class="container">
    <input class="nickname-input" v-model.trim="nickName" placeholder="请输入新的昵称" maxlength="20" />
    <view class="index-title">好的昵称可以让你的朋友更容易记住你。</view>
    <button class="index-title-btn" @click="saveNickname">保存</button>
    </view>
</template>
<script setup>
import { ref } from 'vue'
import { request } from '../utils/request.js'
const nickName = ref('') // 新昵称
const saveNickname = async () => {
    if(!nickName.value) {
        uni.showToast({
            title: '昵称不能为空',
            icon: 'none',
            duration: 3000
        })
        return
    }
  const userInfos = uni.getStorageSync('userInfo')

  await request({
        url: `/user/update/${userInfos.id}`,
        method: 'post',
        data: {
            nickName: nickName.value
        }
        }).then(async (res) => {
            if(res.code !== 200) {
                uni.showToast({
                title: res.data.message || '设置失败',
                icon: 'none',
                    duration: 3000
                })
                return
            }
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2]; // 上一个页面

            uni.$emit('nicknameUpdated');
            uni.showToast({
                title: '修改成功',
                icon: 'success',
            });
            await getUserInfo()

        // 返回上一页
        setTimeout(() => {
            uni.navigateBack();
        }, 1000);
    })
}
const getUserInfo = async() => {
    await request({
        url: '/user/info',
        method: 'POST',
        data: {}
    }).then(res => {
      if(res.code !== 200) {
        uni.showToast({
          title: res.data.message || '获取失败',
          icon: 'none',
                  duration: 3000
        })
        return
      }
      uni.setStorageSync('userInfo', res.data)
    })
}
</script>
<style>
.container {
  padding: 20rpx;
  background-color: #ffffff;
  min-height: 100vh;
}



.nickname-input {
    border-bottom: 2rpx solid #ccc;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 30rpx;
    margin-bottom: 20rpx;
}
.index-title{
    font-size: 26rpx;
    color: #c6c6c6;
    margin-bottom: 20rpx;
}

.index-title-btn {
    background-color: #2b65f6;
    color: #fff;
    border-radius: 10rpx;
    height: 80rpx;
    line-height: 80rpx;
    width: 200px;
    margin-top: 60rpx;
}

</style>